import sys
from pathlib import Path
from loguru import logger
import os
import platform

# 创建日志目录
LOG_DIR = Path("./logs")
LOG_DIR.mkdir(exist_ok=True)

# 定义不同类型日志的配置
log_configs = {
    "info": {
        "path": LOG_DIR / "info.log",
        "level": "INFO",
        "rotation": "1 week",
        "retention": "1 month",
        "format": "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
    },
    "error": {
        "path": LOG_DIR / "error.log",
        "level": "ERROR",
        "rotation": "1 week",
        "retention": "3 months",
        "format": "<red>{time:YYYY-MM-DD HH:mm:ss.SSS}</red> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>\n{exception}"
    },
    "debug": {
        "path": LOG_DIR / "debug.log",
        "level": "DEBUG",
        "rotation": "1 day",
        "retention": "1 week",
        "format": "<blue>{time:YYYY-MM-DD HH:mm:ss.SSS}</blue> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
    },
    "warning": {
        "path": LOG_DIR / "warning.log",
        "level": "WARNING",
        "rotation": "1 week",
        "retention": "2 months",
        "format": "<yellow>{time:YYYY-MM-DD HH:mm:ss.SSS}</yellow> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
    },
    "access": {
        "path": LOG_DIR / "access.log",
        "level": "INFO",
        "rotation": "1 day",
        "retention": "1 month",
        "format": "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan> | {message}"
    }
}

def setup_logging():
    """配置日志系统"""
    # 移除默认的处理器
    logger.remove()
    
    # 添加控制台输出（仅在开发环境）
    if os.getenv("ENVIRONMENT", "development") == "development":
        logger.add(
            sys.stdout,
            level="INFO",
            format="<green>{time:HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
        )
    
    # 为每种日志类型添加处理器
    for config in log_configs.values():
        # Windows下特殊处理
        extra_kwargs = {}
        if platform.system() == "Windows":
            extra_kwargs.update({
                "serialize": True,    # 序列化日志消息，避免并发问题
                "catch": True,        # 捕获日志记录过程中的异常
            })
        
        logger.add(
            config["path"],
            level=config["level"],
            format=config["format"],
            rotation=config["rotation"],
            retention=config["retention"],
            encoding="utf-8",
            enqueue=True,
            backtrace=True,
            diagnose=True,
            **extra_kwargs
        )

def get_logger(name: str):
    """获取命名的日志记录器"""
    return logger.bind(name=name) 